<template>
  <div id="app" v-bind:style="appDivStyle">
      <div class="context" ref="context">
          <!-- 条件查询区 -->
        <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition"
                         ref="form" size="mini">
                  <el-row>
                    <el-col :span="5">
                    <el-form-item :label="$t('playManage.queryLabel.playCode')"   :label-width="queryformLabelWidth">
                        <el-input v-model.trim="formQueryCondition.channelNumber.val" class="queryItemStyle" clearable
                                  :placeholder="$t('playManage.queryLabel.placeholderPlayCode')">
                        </el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="5" :offset="1">
                    <el-form-item :label="$t('playManage.queryLabel.playName')"   :label-width="queryformLabelWidth">
                        <el-input v-model.trim="formQueryCondition.channelName.val" class="queryItemStyle" clearable
                                  :placeholder="$t('playManage.queryLabel.placeholderPlayName')">
                        </el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="5" :offset="1">
                    <el-form-item :label="$t('playManage.queryLabel.eName')" :label-width="queryformLabelWidth">
                        <el-input v-model.trim="formQueryCondition.channelSName.val" class="queryItemStyle" clearable
                                :placeholder="$t('playManage.queryLabel.placeholderEName')" >
                        </el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="5" :offset="1">
                    <el-form-item :label="$t('playManage.queryLabel.sendStatus')" :label-width="queryformLabelWidth">
                      <el-select v-model="formQueryCondition.sendtoState.val" class="queryItemStyle" :placeholder="$t('queryLabel.selectOp')">
                        <el-option :label="$t('playManage.label.all')" value=""></el-option>
                        <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in sendStatus"></el-option>
                      </el-select>
                    </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <!-- 状态 -->
                    <el-col :span="5">
                        <el-form-item :label="$t('PublisherManage.queryLabel.status')"  :label-width="queryformLabelWidth">
                            <el-select v-model="formQueryCondition.isEnable.val" class="queryItemStyle">
                                <el-option :label="$t('label.all')" value=""></el-option>
                                <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                                <!-- <el-option :label="$t('label.available')" value="Available"></el-option>
                                <el-option :label="$t('label.invalid')" value="Invalid"></el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="24">
                    <div style="text-align:right">
                        <el-form-item>
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'saveBtnText'}" type="primary" @click="onAdd('saveBtnText')" >{{$t('playManage.btnText.addBtnText')}}</el-button>
                        <!--下发记录-->
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'sendRecordBtnText'}" type="primary" @click="sendRecord('sendRecordBtnText')" >{{$t('playManage.btnText.sendRecord')}}</el-button>
                            <!--批量下发-->
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'batchSendBtnText'}" type="primary" @click="onBatchSend('batchSendBtnText')">{{$t('playBillManage.btnText.sendBatchBtnText')}}</el-button>
                         <!--导入-->
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'ImportBtnText'}" type="primary" @click="openUploadDlg('ImportBtnText')" icon="el-icon-upload2" :loading="loading">{{ $t('playManage.btnText.importBtnText') }}</el-button>
                        <!--导入模板下载-->
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'downloadTemplate'}" type="primary" @click="downloadTemplate('downloadTemplate')" icon="el-icon-download" :loading="loading">{{ $t('playManage.btnText.downloadTemplate') }}</el-button>
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'resetBtnText'}" type="primary" @click="onReset" >{{$t('playManage.btnText.resetBtnText')}}</el-button>
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'queryBtnText'}" type="primary" @click="onQuery('queryBtnText')" icon="el-icon-refresh">{{$t('playManage.btnText.queryBtnText')}}</el-button>
                        </el-form-item>
                    </div>
                    </el-col>
                  </el-row>
                </el-form>
            </div>

            <!-- 数据展示区 -->
            <div class="dataBox" ref="dataBox">

                <el-table v-if="isInit" ref="singleTable"
                            :data="tableData"
                            :height="tableHeight"
                            @sort-change="sortChange"
                            @selection-change="changeBox"
                            v-loading="loading" size="mini"
                            style="width: 100%;" stripe=stripe border=border>
                    <!-- <el-table-column type="index"  width="70" fixed="left"
                        :label="$t('table.xh')" align="center">
                    </el-table-column> -->
                    <el-table-column type="selection" width="55" fixed="left" align="center" :selectable="selectable">
                    </el-table-column>
                    <el-table-column fixed="left" :label="$t('table.op')" min-width="320">
                        <template slot-scope="scope">
                          <!-- 编辑 -->
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'editBtnText'}" size="gv" icon="el-icon-edit"
                                :loading="loading" @click="edit(scope.$index, scope.row,'editBtnText')"
                                    >{{ $t('playManage.btnText.editBtnText') }}</el-button>
                                    <!-- 详情 -->
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'detailsBtnText'}" size="gv" icon="el-icon-search"
                                :loading="loading" @click="onDetails(scope.$index, scope.row,'detailsBtnText')"
                                  >{{ $t('playManage.btnText.detail') }}</el-button>
                            <!--下发-->
                            <el-button size="gv" icon="el-icon-delete"
                                v-permission="{menuCode: menuCode, resourceCode: 'sendBtnText'}"
                                    type="danger" :loading="loading" @click="onSend(scope.$index, scope.row,'sendBtnText')"
                                    :disabled="scope.row.sendtoState=='DownAlready'">{{ $t('ParentAssetIssuance.btnText.sendBtnText') }}</el-button>
                            <!-- <el-button v-permission="{menuCode:menuCode,resourceCode:'passBtnText'}" size="gv" icon="el-icon-delete" type="danger"
                                :loading="loading" @click="logoffRow(scope.$index, scope.row)"
                                            >{{ $t('btnText.logoffBtnText') }}</el-button> -->
                                            <!-- 删除 -->
                                  <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable=='Invalid'" v-permission="{menuCode: menuCode, resourceCode: 'deleteBtnText'}"
                                        type="danger" :loading="loading" @click="deleteRow(scope.$index, scope.row,'deleteBtnText')"
                                        >{{ $t('btnText.deleteBtnText') }}</el-button>
                                        <!-- 注销 -->
                                 <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable=='Available'"
                                        v-permission="{menuCode:menuCode,resourceCode:'passBtnText'}"
                                        type="danger" :loading="loading" @click="logoffRow(scope.$index, scope.row,'passBtnText')"
                                        >{{ $t('btnText.logoffBtnText') }}</el-button>
                                <!-- 恢复 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable==='Invalid'"
                                v-permission="{menuCode: menuCode,resourceCode: 'recoveryBtnText'}"
                                      type="danger" :loading="loading" @click="revertLogoffRow(scope.$index, scope.row,'recoveryBtnText')"
                                     >{{ $t('btnText.recoveryBtnText') }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="channelNumber" min-width="110" fixed="left"
                        :label="$t('playManage.tableText.playCode')" sortable="custom" sort-by="channelNumber">
                    </el-table-column>
                    <el-table-column prop="channelName" min-width="180" fixed="left"
                        :label="$t('playManage.tableText.playName')" sortable="custom" sort-by="channelName">
                    </el-table-column>
                    <el-table-column prop="channelSName" min-width="110"
                        :label="$t('playManage.tableText.eName')" sortable="custom" sort-by="channelSName">
                    </el-table-column>
                    <el-table-column prop="channelAlName" min-width="180"
                        :label="$t('playManage.tableText.playByName')" sortable="custom" sort-by="channelAlName">
                    </el-table-column>
                    <el-table-column prop="sendtoStateName" min-width="140"
                        :label="$t('playManage.tableText.status')" sortable="custom" sort-by="sendtoState">
                    </el-table-column>
                    <el-table-column min-width="180"
                        :label="$t('playManage.tableText.playLogo')" >
                        <template slot-scope="scope">
                           <img :src="scope.row.channelLogo" width="122" height="53"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="modifier" min-width="140"
                        :label="$t('playManage.tableText.modifier')" sortable="custom" sort-by="modifier">
                    </el-table-column>
                    <el-table-column prop="lastUpdatedDate" min-width="140"
                        :label="$t('playManage.tableText.lastUpdatedDate')" sortable="custom" sort-by="lastUpdatedDate">
                    </el-table-column>
                </el-table>


            </div>
        </div>

        <!-- 翻页选择区 -->
        <div class="pageBox">
            <el-pagination @size-change="sizeChange"
                            @current-change="currentPageChange"
                            :current-page="pager.curPage"
                            :page-sizes="pager.sizes"
                            :page-size="pager.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
            </el-pagination>
        </div>

         <!--新增对话框-->
        <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowEditForm" top="5vh" :close-on-click-modal="false">
            <el-form :model="editForm" ref="editForm" size="mini"
                     :label-position="editFormPosition" status-icon=status-icon :rules="editRules">
                <el-input v-model.trim="editForm.keyId"  v-show="false"></el-input>
                <!--频道号-->
                <el-form-item :label="$t('playManage.editLabel.playCode')" :label-width="editformLabelWidth" prop="channelNumber">
                    <el-input v-model.trim="editForm.channelNumber" maxlength="20" :placeholder="$t('playManage.editLabel.placeholderPlayCode')"></el-input>
                </el-form-item>
                <!--频道名称-->
                <el-form-item :label="$t('playManage.editLabel.playName')" :label-width="editformLabelWidth" prop="channelName">
                    <el-input v-model.trim="editForm.channelName" :placeholder="$t('playManage.editLabel.placeholderPlayName')"></el-input>
                </el-form-item>
                <!--英文简称-->
                <el-form-item :label="$t('playManage.editLabel.eName')" :label-width="editformLabelWidth" prop="channelSName">
                    <el-input v-model.trim="editForm.channelSName" :placeholder="$t('playManage.editLabel.placeholderEName')"></el-input>
                </el-form-item>
                <!--频道别名-->
                <el-form-item :label="$t('playManage.editLabel.playByName')" :label-width="editformLabelWidth" prop="channelAlName">
                    <el-input v-model.trim="editForm.channelAlName"
                              :placeholder="$t('playManage.editLabel.placeholderPlayByName')"></el-input>
                </el-form-item>
                <!--台标 -->
                <el-form-item :label="$t('playManage.editLabel.playLogo')" :label-width="editformLabelWidth" prop="channelLogo">
                    <!-- <el-input  v-model.trim="editForm.channelLogo" maxlength="300"  type="file" ></el-input> -->
                    <!-- <el-input v-model.trim="editForm.channelLogo"  width="120"></el-input> -->
                    <!-- <el-upload size="tiny" ref="upload" :action="uploadUrl" :data="editForm" accept=".png,.jpg, .jpeg"
                        :multiple="false" :on-preview="handlePreview" :on-remove="handleRemove" :on-error = "error" :on-success = "success" :file-list="fileList" :auto-upload="false"
                        :limit="1" :on-exceed="handleExceed">
                        <el-button :loading="loading" round slot="trigger" size="mini" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传800*200的jpg/png文件</div>
                    </el-upload> -->
                    <el-input v-model.trim="editForm.channelLogo"  width="120" v-show="false"></el-input>
                    <el-upload
                        class="avatar-uploader"
                        :action="action"
                        :data="{site:'public',type:'live_logo'}"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer">
                <!--取消按钮-->
                <el-button size="mini" @click="isShowEditForm = false" :loading="loading">{{ $t('playManage.btnText.cancelBtnText') }}</el-button>
                <!--保存按钮-->
                <el-button size="mini" type="primary" @click="submitForm('editForm',currentResCode)" :loading="loading">{{ $t('playManage.btnText.saveBtnText') }}</el-button>
            </div>
        </el-dialog>

        <!--详情对话框-->
        <el-dialog :title="$t('playManage.label.detail')" :visible.sync="isShowEditForm2" top="5vh" :close-on-click-modal="false">
            <el-form :model="editForm" ref="editForm" size="mini"
                     :label-position="editFormPosition" status-icon=status-icon :rules="editRules">

                <el-input v-model.trim="editForm.keyId"  v-show="false"></el-input>
                <!--频道号/频道名称-->
                <el-row class="datarow bgrow">
                    <el-col class="labcol" :span="labelSpan">{{$t('playManage.editLabel.playCode') + ":"}}</el-col>
                    <el-col class="datacol" :span="dataSpan">{{editForm.channelNumber}}</el-col>
                    <el-col class="labcol" :span="labelSpan">{{$t('playManage.editLabel.playName') + ":"}}</el-col>
                    <el-col class="datacol" :span="dataSpan">{{editForm.channelName}}</el-col>
                </el-row>
                <!--英文简称/频道别名-->
                <el-row class="datarow">
                  <el-col class="labcol" :span="labelSpan">{{$t('playManage.editLabel.eName')}}</el-col>
                  <el-col class="datacol" :span="dataSpan">{{editForm.channelSName}}</el-col>
                  <el-col class="labcol" :span="labelSpan">{{$t('playManage.editLabel.playByName')}}</el-col>
                  <el-col class="datacol" :span="dataSpan">{{editForm.channelAlName}}</el-col>
                </el-row>
                <!--台标-->
                <el-row class="datarow bgrow">
                  <el-col class="labcol" :span="labelSpan">{{$t('playManage.editLabel.playLogo')}}</el-col>
                  <el-col class="datacol" :span="dDataSpan"><img v-bind:src="editForm.channelLogo" height="53" width="122"></el-col>
                  <!-- <el-col class="datacol" :span="dDataSpan"><img v-bind:src="editForm.channelLogo" height="85" width="150"></el-col> -->
                </el-row>
            </el-form>

        </el-dialog>

        <!-- 下发对话框 -->
        <transition enter-active-class="animated rotateIn" leave-active-class="animated rotateOut">
        <el-dialog :title="$t('playManage.label.launchDialogTitle')" :visible.sync="isShowEditForm3" top="5vh" @close="refresh" :close-on-click-modal="false">
            <el-form :inline="true" :model="sendForm" ref="sendForm" size="mini"
                     :label-position="editFormPosition" status-icon=status-icon :rules="sendRules">
            <el-row>
                <el-form-item :label="$t('')" :label-width="editformLabelWidth" prop="siteList">
                    <el-checkbox-group v-model="sendForm.siteList" >
                        <el-checkbox :value="item.siteName" :key="item.keyId" :label="item.keyId" v-for="item in siteData">{{item.siteName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-row>
            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isShowEditForm3 = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="comfirmSend('sendForm',currentResCode)" :loading="loading">{{ $t('btnText.sendConfirmBtnText') }}</el-button>
            </div>
        </el-dialog>
      </transition>

      <!--下发记录页面-->
      <el-dialog :title="$t('playManage.label.sendRecord')" :visible.sync="isShowInfoForm4" top="5vh" width="1200px" :close-on-click-modal="false">
            <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition2"
                         ref="form" size="mini">
                  <el-row>
                    <el-col :span="7">
                    <el-form-item :label="$t('playManage.queryLabel.playCode')"   :label-width="queryformLabelWidth">
                        <el-input v-model.trim="formQueryCondition2.channelNumber.val" class="queryItemStyle" clearable
                                  :placeholder="$t('playManage.queryLabel.placeholderPlayCode')">
                        </el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="7" :offset="1">
                    <el-form-item :label="$t('playManage.queryLabel.playName')"   :label-width="queryformLabelWidth">
                        <el-input v-model.trim="formQueryCondition2.channelName.val" class="queryItemStyle" clearable
                                  :placeholder="$t('playManage.queryLabel.placeholderPlayName')">
                        </el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="7" :offset="1">
                    <el-form-item :label="$t('assetsDR.queryLabel.status')"   :label-width="queryformLabelWidth">
                        <el-select v-model="formQueryCondition2.state.val" class="queryItemStyle">
                            <el-option :label="$t('assetsDR.label.all')" value=""></el-option>
                            <el-option :value="drug.valueText" :key="drug.valueText" :label="drug.valueText" v-for="drug in States"></el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="7">
                    <el-form-item :label="$t('playBillManage.queryLabel.startTime')"   :label-width="queryformLabelWidth">
                        <el-date-picker v-model.trim="formQueryCondition2.createDateStart.val" class="queryItemStyle" clearable
                                :placeholder="$t('queryLabel.selectOp')" type="datetime" :picker-options="pickerOptionsStart"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                                <!-- :picker-options="pickerOptionsStart" -->
                        </el-date-picker>
                    </el-form-item>
                    </el-col>
                    <el-col :span="7" :offset="1">
                    <el-form-item :label="$t('playBillManage.queryLabel.timeTo')"   :label-width="queryformLabelWidth">
                        <el-date-picker v-model.trim="formQueryCondition2.createDateEnd.val" class="queryItemStyle" clearable
                                :placeholder="$t('queryLabel.selectOp')" type="datetime" :picker-options="pickerOptionsEnd"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                                <!-- :picker-options="pickerOptionsEnd" -->
                        </el-date-picker>
                    </el-form-item>
                    </el-col>
                  </el-row>

                <el-row>
                  <el-col :span="24">
                    <div style="text-align:right">
                        <el-form-item>
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'resetBtnText'}" type="primary" @click="onReset2('form')">{{ $t('btnText.resetBtnText') }}</el-button>
                            <el-button v-permission="{menuCode:menuCode,resourceCode:'queryBtnText'}" type="primary" @click="onQuery2('queryBtnText')" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                        </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                </el-form>
            </div>
            <el-table v-if="isInit" ref="singleTable"
                                :data="tableData2"
                                :height="tableHeight"
                                @sort-change="sortChange2"
                                v-loading="loading" size="mini"
                                style="width: 100%;" stripe=stripe border=border>
                        <el-table-column prop="channelNumber" min-width="140" fixed="left"
                                            :label="$t('assetsDR.tableText.assetsCode')" sortable="custom" sort-by="channelNumber">
                        </el-table-column>
                        <el-table-column prop="channelName" min-width="190" fixed="left"
                                            :label="$t('assetsDR.tableText.assetsName')" sortable="custom" sort-by="channelName">
                        </el-table-column>
                        <el-table-column prop="siteName" min-width="150"
                        :label="$t('assetsDR.tableText.siteName')" sortable="custom" sort-by="siteName">
                        </el-table-column>
                        <!-- <el-table-column prop="vChannelLendLogEntity.type" min-width="150"
                        :label="$t('assetsDR.tableText.type')" sortable="custom" sort-by="type">
                        </el-table-column> -->
                        <el-table-column :label="$t('assetsDR.tableText.status')" min-width="120" sortable="custom" prop="state" sort-by="state">
                        </el-table-column>
                        <el-table-column :label="$t('assetsDR.tableText.message')" min-width="220" sortable="custom" prop="message" sort-by="message">
                        </el-table-column>
                        <el-table-column :label="$t('assetsDR.tableText.createTime')" min-width="180" sortable="custom" prop="createDate" sort-by="createDate">
                        </el-table-column>

            </el-table>
               <!-- 翻页选择区 -->
        <div class="pageBox">
            <el-pagination @size-change="sizeChange2"
                            @current-change="currentPageChange2"
                            :current-page="pager2.curPage"
                            :page-sizes="pager2.sizes"
                            :page-size="pager2.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager2.total">
            </el-pagination>
        </div>
        </el-dialog>

      <el-dialog :title="this.$i18n.t('label.import')" width="400px" :visible.sync="dlgUploadVisible" :close-on-click-modal="false">
      <upload-file
        v-bind:uploadUrl="uploadCourseMaterialUrl"
        v-bind:acceptFileType="'.xlsx'"
        v-bind:uploadParams="uploadCourseMaterialParams"
        v-bind:fileList="fileList"
        v-bind:autoUpload="false"
        v-bind:fileLimit="1"
        v-bind:selectName="this.$i18n.t('label.selectName')"
        v-bind:uploadBtn="this.$i18n.t('label.submit')"
        v-bind:fileTypeText="'xlsx'"
        v-bind:submitSuccess="submitUploadSuccess"
        v-bind:menuCode="menuCode"
      ></upload-file>
    </el-dialog>
  </div>


</template>

<script>

import comBaseVue from '../../baseViewModel';
import { throws } from 'assert';

export default {
  mixins: [comBaseVue],
  name:'playManage',
  components: {
    'upload-file': () => import('../common/UploadFile')
  },
  props: {
    // isNeedGoBack:Boolean,
    // // curRootAssets: Object,
    // curProps: null
    menuCode: String
  },
  data () {

    return {
        isShowInfoForm: false,
        isShowEditForm3: false,
        tableData2: [],
        channelData:[],
        activeName: 'first',
        isInit:false,
        tableHeight:100,
        labelSpan:4,
        dataSpan:8,
        // 是否显示编辑面板
        isShowEditForm: false,
        isShowEditForm2: false,
        isShowInfoForm4:false,
        enables:[],
        sendStatus:[],
        siteData:[],
        States:[],
        multipleSelection: [],
         // 分页对象
            pager2: {
                curPage: 1,
                sizes: [20, 30, 50, 100, 200, 400],
                curSize: 20,
                total: 0
            },
        appDivStyle:{
            height:this.$store.getters.appHeight,
        },
        // 排序对象
            sort2: {
                key: "keyId",
                dir: "Desc"
            },
        modelName:"com.ispr.iptv.entity.live.ChannelEntity",
        modelName2:"com.ispr.iptv.entity.live.VChannelLendLogEntity",
        // 查询条件
        formQueryCondition: {
            channelNumber: {
              key: 'channelNumber',
              op: '=',
              val: ''
            },
            channelName:{
              key:'channelName',
              op:'LIKE',
              val:''
            },
            channelSName:{
              key:'channelSName',
              op:"LIKE",
              val:''
            },
            channelAlName:{
              key:'channelAlName',
              op:'LIKE',
              val:''
            },
            sendtoState:{
              key:'sendtoState',
              op: '=',
              val:''
            },
            isEnable:{
              key:'isEnable',
              op: '=',
              val:'Available'
            }
        },
        // 下发记录查询条件
        formQueryCondition2: {
            channelNumber: {
                key: 'channelNumber',
                op: 'LIKE',
                val: ''
            },
            channelName: {
                key: 'channelName',
                op: 'LIKE',
                val: ''
            },
            createDateStart: {
                key: 'createDate',
                val: '',
                op:'>=',
                group:'1'//时间区间查询，两个group的值不一样进行与运算否则进行或运算
            },
            createDateEnd: {
                key: 'createDate',
                val: '',
                op:'<=',
                group:'2'
            },
            state:{
              key: 'state',
              op: '=',
              val: ''
            },
            sendtoState:{
              key: 'sendToState',
              op: '=',
              val: 'DownAlready'
            },
        },

         // 编辑面板绑定的对象
        editForm: {
            keyId: 0,
            version: 0,
            channelNumber:"",
            channelName:"",
            channelSName:"",
            channelAlName:"",
            channelLogo:"",
            sendtoState:"StayDown",
            isEnable:"Available"
        },
        // 编辑面板的验证规则
        editRules: {
            channelNumber: [{ required: true, message: this.$i18n.t('playManage.rules.playCode'), trigger: 'blur' }],
            channelName: [{ required: true, message: this.$i18n.t('playManage.rules.playName'), trigger: 'blur' }],
            parentSite: [{ required: true, message: this.$i18n.t('playManage.rules.parentSite'), trigger: 'blur' }],
            channelLogo: [{ required: true, message: this.$i18n.t('playManage.rules.playLogo'), trigger: 'change' }],
        },

        sendRules: {
            siteList: [{ required: true, message: this.$i18n.t('ParentAssetIssuance.rules.sendCheckTip'), trigger: 'blur' }],
        },
        //下发
        sendForm: {
            siteList: [],//下发到的站点
            sendType:"",
        },
        pickerOptionsStart:{
          disabledDate: time => {
            let endDateVal = this.formQueryCondition.playbillEnd.val;
            if (endDateVal) {
              // alert(time.getTime());
              return time.getTime() > new Date(endDateVal).getTime();
            }
          }
        },
      pickerOptionsEnd: {
        disabledDate: time => {
          let beginDateVal = this.formQueryCondition.playbillStart.val;
          if (beginDateVal) {
            return (
              time.getTime() <
              new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000

            );
          }
        }
      },

        //////////////////////////////////上传文件/////////////////////
        imageUrl: '',
        uploadUrl: '/api/channel/channelSave', //请求地址
        params: null, //参数
        fileList: [], //文件集合
        //////////////////////////////////文件导入/////////////////////
        uploadCourseMaterialUrl: '/api/import/upload',
        uploadCourseMaterialParams: null,
        dlgUploadVisible: false
    }
  },
  methods:{
    selectable(row,index){
        if((row.sendtoState !=="DownAlready")){
          return true;
        }else{
          return false;
        }
      },
    // 分页容量变化
        sizeChange2: function(val) {
            this.pager2.curPage = 1;
            this.pager2.curSize = val;
            this.queryTable2();
        },
         // 分页按钮
        currentPageChange2: function (val) {
            this.pager2.curPage = val;
            this.queryTable2();
        },
          // 排序回调函数
        sortChange2: function(sortObj) {
            // alert(JSON.stringify(sortObj));
            // console.log(sortObj);
            this.pager2.curPage = 1;
            this.sort2.key = sortObj.column.sortBy;
            if (sortObj.order == "ascending") {
                this.sort2.dir = "asc";
            } else {
                this.sort2.dir = "desc";
            }
            this.queryTable2();
        },
    onAdd: function(rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.isShowEditForm = true;
        // this.uploadUrl = '/api/channel/channelSave';
        if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields();
        }
        this.editForm.keyId = "";
        this.editForm.version = "";
        this.editForm.channelNumber = "";
        this.editForm.channelName = "";
        this.editForm.channelSName = "";
        this.editForm.channelAlName = "";
        this.editForm.channelLogo = "";
        this.imageUrl = '';
        this.fileList = [];
        this.curCommand = "ChannelSaveProc";
        this.canEditCode = false;
    },

    // 编辑按钮回调事件
    editCallback: function(isSuccess, json) {
          //  console.info(json);
      if (isSuccess) {
        this.curCommand = "ChannelUpdateProc";
        // this.uploadUrl = '/api/channel/channelUpdate';
        this.isShowEditForm = true;
        this.isUpload = false;//是否上传文件
        if (this.$refs["editForm"]) {
          this.$refs["editForm"].resetFields();
        }
        this.editForm.keyId = json.keyId;
        this.editForm.version = json.version;
        this.editForm.channelNumber = json.channelNumber;
        this.editForm.channelName = json.channelName;
        this.editForm.channelSName = json.channelSName;
        this.editForm.channelAlName = json.channelAlName;
        this.editForm.channelLogo = json.channelLogo;
        this.imageUrl = json.channelLogo;
        this.fileList = [{name:json.channelLogo,uid:1,percentage:0,raw:{uid:1},status:"ready"}];

        // this.canEditCode = true;
      } else {
        this.$message({
          message: json.msg,
          type: "warning"
        });
      }
    },
    //下发记录
    sendRecord:function(rescode){
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      this.isShowInfoForm4 = true;
      this.onReset2();
      this.onQuery2();
    },
      // 查询按钮
        onQuery2: function() {
            this.pager2.curPage = 1;
            this.queryTable2();
        },
         // 查询网格数据
        queryTable2: function() {
            this.loading = true;
            this.queryModel(this.modelName2,"Query",this.formQueryCondition2,this.pager2,this.sort2,this.setTableData2)
            // this.queryModel(this.modelName2,"Query",{sendToState: {
            //   key: 'sendToState',
            //   op: '=',
            //   val: 'DownAlready'
            // }},this.pager2,this.sort2,this.setTableData2)
        },
        // 查询网格数据成功后的回调
        setTableData2: function(isSuccess,json) {
            this.loading = false;
            try{
                if (isSuccess) {
                    //alert(JSON.stringify(json));
                    this.pager2.total = json.total;
                    this.tableData2 = [];
                    for (var i = 0; i < json.list.length; i++) {
                        this.tableData2.push(json.list[i]);
                    }

                }
                else {
                    this.$message.error(json.msg);
                }
            }
            catch(e){
                alert(e);
            }
        }, // 重置
    onReset2:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition2.channelNumber.val = "";
        this.formQueryCondition2.channelName.val = "";
        this.formQueryCondition2.createDateStart.val = "";
        this.formQueryCondition2.createDateEnd.val = "";
        this.formQueryCondition2.sendtoState.val = "DownAlready";
        this.formQueryCondition2.state.val = "";

    },
     //详情按钮
    onDetails: function(index, row,rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      console.info(row.channelLogo);
      //dataAccess.queryDomainModelByKeyID(this, modelName, "Query", row.keyID, true, this.$options.methods.editCallback);
      this.queryModelByKeyID(
        this.modelName,
        row.keyId,
        "Query",
        this.onDetailsCallback
      );
    },

    onDetailsCallback: function(isSuccess, json)  {
      if (isSuccess) {

        this.isShowEditForm2 = true;
         if (this.$refs["editForm"]) {
           this.$refs["editForm"].resetFields();
         }
        this.editForm.keyId = json.keyId;
        this.editForm.version = json.version;
        this.editForm.channelNumber = json.channelNumber;
        this.editForm.channelName = json.channelName;
        this.editForm.channelSName = json.channelSName;
        this.editForm.channelAlName = json.channelAlName;
        this.editForm.parentSite = json.parentSite;
        this.editForm.channelLogo = json.channelLogo;
        this.canEditCode = false;
      } else {
        this.$message({
          message: json.msg,
          type: "warning"
        });
      }
    },

    refresh: function(){
        if (this.$refs['sendForm']) {
            this.$refs['sendForm'].resetFields();
        }
        this.sendForm.siteList = [];
    },
    //单个下发
    onSend: function(index, row,rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.sendForm.sendType = "single";
        this.singleSend = {};
        let keyId = row.keyId;
        let version = row.version;
        let sendtoState = "DownAlready";
        this.channelData = [];
        let data = {"keyId":keyId,"version":version,"sendtoState":sendtoState};
        this.singleSend = data;
        this.isShowEditForm3 = true;
    },
    changeBox: function(val) {
            this.multipleSelection = [];
            for (let i=0;i<val.length;i++){
                let keyId = val[i].keyId;
                let version = val[i].version;
                let sendtoState = "DownAlready";
                let channelId = val[i].channelId;
                let data = {"keyId":keyId,"version":version,"sendtoState":sendtoState,"channelId":channelId};
                this.multipleSelection.push(data);
            }
        },
    onBatchSend: function(rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      if(this.multipleSelection.length==0){

          this.$message({
              message: this.$i18n.t("AssetIssuance.label.checkTip"),
              type: 'warning'
          });
          return;
      }
      else{
        let chId="";
        for(var i=0;i<this.multipleSelection.length;i++){
          if(chId!="" && chId!=this.multipleSelection[i].channelId){
            this.$message({
                message: this.$i18n.t("playBillManage.message.error"),
                type: 'warning'
            });
            return;
          }else{
            chId=this.multipleSelection[i].channelId;
          }
        }
        this.channelData = [];
      }
      this.sendForm.sendType = "batch";
      this.isShowEditForm3 = true;
    },
    // 提交下发界面数据
    comfirmSend: function (formName,rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        let dataList = [];//最终传给后台的总数据
        let siteListJson = [];//站点的数据
        for (let i=0;i<this.sendForm.siteList.length;i++){
            let siteId = this.sendForm.siteList[i];
            let resType = "C";
            let state = "Untreated";
            let data = {"siteId":siteId,"resType":resType,"state":state};
            siteListJson.push(data);
        };
        if(this.sendForm.sendType=="batch"){
            for(let i=0;i<this.multipleSelection.length;i++){
                let temp = this.multipleSelection[i];
                temp.siteList = siteListJson;
                dataList.push(temp);
            }
        }else if(this.sendForm.sendType=="single"){
            this.singleSend.siteList = siteListJson;
            dataList.push(this.singleSend);
        }
        this.$refs[formName].validate(function (valid) {
            if (valid) {
                _this.loading = true;
                _this.procCommand("MediaSendToProc",
                _this.modelName,
                "Default",
                {
                    "dataList":dataList,
                },
                null,
                _this.comfirmSendCallback);
            } else {
                return false;
            }
        });
    },
    // 执行命令后的回调函数
    comfirmSendCallback: function (isSuccess,json) {
        this.loading = false;
        if(isSuccess){
            this.isShowEditForm3 = false;
            this.$message({
                message: this.$i18n.t("message.successTip"),//resource.message.successTip,
                type: 'success'
            });
            this.queryTable();
        }
        else
        {
            this.$message({
                            message: json.msg,
                            type: 'warning'
                            });
        }
    },

     //站点复选框数据 siteData
    findSite: function(){
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.Site",//修改为被查询的实体地址
                opKey: "Query",//后台编写相应的接口实现方法，主要负责转化类型
                params: [{key: 'isEnable',op: '=',val: 'Available'}],
                userInfo: this.getUserInfo()
            };
            var _this = this;
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    console.log(_this.siteData)
                    if (res.data.code == "SUCCESS") {
                        _this.siteData = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.siteData.push(res.data.data[i]);
                        }
                    } else {
                        // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                });
    },

    setSiteCallback: function(isSuccess,json){
        try{
            if (isSuccess) {
                for (var i = 0; i < json.data.length; i++) {
                    this.approvalStatusData.push(json.data[i]);
                }
            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },


     // 重置
    onReset:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition.channelNumber.val = "";
        this.formQueryCondition.channelName.val = "";
        this.formQueryCondition.channelSName.val = "";
        this.formQueryCondition.sendtoState.val = "";
    },



      handleAvatarSuccess(res, file) {
        //alert(res.data);
        //alert(URL.createObjectURL(file.raw));
        this.imageUrl = res.data;
        this.editForm.channelLogo = res.data;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 1;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 1MB!');
        }
        return isJPG && isLt2M;
      },
    /////////////////////////////文件上传//////////////////////////////////////////////
    //表单提交
    submitUpload: function submitUpload (rescode) {
      //  debugger
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        // alert("上传");
        var B = false;
        this.$refs["editForm"].validate(function (valid) { if (!valid){B = true;} });//数据表单验证
        if(B){return false;}
        // alert("上传");
        //文件表单验证
        if (!this.$refs.upload.uploadFiles.length || this.$refs.upload.uploadFiles.length <= 0) {
            this.$message.warning('您未选择上传文件');
            return false;
        }
        window.setTimeout(this.$refs.upload.submit(),100);
    },
    // 移除文件
    handleRemove: function handleRemove (file, fileList) {
      this.$message.success('移除成功！');
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview: function handlePreview (file) {

    },
    // 文件超出个数限制时的钩子
    handleExceed: function handleExceed (files, fileList) {
      this.$message('上传文件数量超过限制');
    },
    //文件上传失败时的钩子
    error: function error () {
      this.$message.error('上传失败！');
    },
    //文件上传成功时的钩子
    success: function success (response, file, fileList) {
      if (response.code === 'SUCCESS') {
        this.$message.success('上传成功！');
        this.isShowEditForm = false;
        this.onQuery();
      } else {
        this.$message.error(response.msg);
      }
    },
    /////////////////////////////////////////上传结束///////////////////////////////////////////////////////

    /////下载导入模板
    downloadTemplate: function downloadTemplate (rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      this.downloadByIdOrName(this, '/import/downtemplate', 'fileName', '频道信息导入模板.xlsx', '频道信息导入模板.xlsx');
    },


    /////////////////////////////////// 频道信息导入 ///////////////////////////////////////////
    // 打开导入资材关系的dialog
    openUploadDlg: function openUploadDlg (rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      let _this = this;
      // this.$alert('注意：导入后将会覆盖原有的所有数据，是否继续？', '提示', {
      //   confirmButtonText: '确定',
      //   callback: action => {
      //     if (action === 'confirm') {
            // 初始化错误文件下载id
            _this.errorTaskId = null;
            // 清空文件列表
            _this.fileList = [];
            _this.dlgUploadVisible = true;
            // this.uploadPhorderUrl = this.baseUrl+'/import/upload';
            _this.uploadCourseMaterialParams = {'className': _this.modelName};
      //     }
      //   }
      // });
    },

    submitUploadSuccess: function submitUploadSuccess (response, file, fileList,rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      if (response.code === 'SUCCESS') {
        if (response.data.status === '0') {
          this.dlgUploadVisible = false;
          this.$message.success('导入成功');
          this.fileList = []; // 清空上传文件列表
          // 刷新表格数据
          this.onQuery();
          return false;
        }
        if (response.data.status === '3') {
          let _this = this;
          this.$alert('导入失败，是否下载失败原因文件?', '提示', {
            confirmButtonText: '确定',
            callback: function callback (action) {
              if (action === 'confirm') {
                _this.downloadByIdOrName(_this, '/import/downerr', 'taskId', response.data.taskId, response.data.errFileName);
              } else {
                _this.$message({
                  type: 'info',
                  message: '已取消'
                });
              }
            }
          });
          this.fileList = []; // 清空上传文件列表
          this.dlgUploadVisible = false;
        }
      } else {
        this.$message.error(response.msg);
      }
    },
//////////////////////////////////////////////////////////////////////////////////////////////////

    //下拉框
    findEnables:function(){
      this.findByTypeCode("10001",this.setEnables);
    },

    setEnables:function(isSuccess,json){
      try{
        if(isSuccess){
          this.enables = [];
          for(var i = 0 ; i < json.data.length ; i++){
            this.enables.push(json.data[i]);
          }
        }else{
          this.$message.error(json.msg);
        }
      }
      catch(e){
        alert(e);
      }
    },
    //下拉框
    findSendStatus:function(){
      this.findByTypeCode("10011",this.setSendStatus);
    },

    setSendStatus:function(isSuccess,json){
      try{
        if(isSuccess){
          this.sendStatus = [];
          for(var i = 0 ; i < json.data.length ; i++){
            this.sendStatus.push(json.data[i]);
          }
        }else{
          this.$message.error(json.msg);
        }
      }
      catch(e){
        alert(e);
      }
    },
     //编辑面板提交后调用，设置唯一性验证条件
    setEditFormCheck:function setEditFormCheck(){
        if(this.curCommand == "ChannelSaveProc"){
            this.editFormCheck = [{
                    key: 'channelNumber',
                    op: '=', // 操作符
                    val: this.editForm.channelNumber// 查询的值
                }];
        }else if(this.curCommand == "ChannelUpdateProc"){
            this.editFormCheck = [{
                    key: 'channelNumber',
                    op: '=', // 操作符
                    val: this.editForm.channelNumber// 查询的值
                },
                {
                    key: 'keyId',
                    op: '<>', // 操作符
                    val: this.editForm.keyId
                }];
        }

    },
    findStates:function(){
      this.findByTypeCode("10015",this.setStates);
    },
    setStates:function(isSuccess,json){
      try{
        if(isSuccess){
          this.States=[];
          for(var i=0 ; i < json.data.length ; i++){
            this.States.push(json.data[i]);
          }
        }else{
          this.$message.error(json.msg);
        }
      }catch(e){
        alert(e);
      }
    },

     initTable:function(){
        this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
        this.isInit = true;
    },
    enterDown(){
      var g = this
      if(g.isShowEditForm){
        g.submitForm('editForm',g.currentResCode)
      }else if(g.isShowEditForm2){
        // 详情
        g.isShowEditForm2 = false
      }else if(g.isShowEditForm3){
        g.comfirmSend('sendForm',g.currentResCode)
      }else if(g.isShowInfoForm4){
        g.onQuery2()
      }else if(!g.loading){
        g.onQuery()
      }
    }

  },
  computed: {
      dDataSpan:function(){
          return 24 - this.labelSpan;
      }
  },
  watch:{
    'editForm.channelNumber': function(newVal,oldVal){
      if(newVal<0){
          this.$refs['inputNumber']._data.currentValue = "";
        this.editForm.channelNumber = "";
      }
    }
},
  mounted: function mounted() {
    this.findSite();
    this.findEnables();
    this.findSendStatus();
    this.onQuery();
    // this.findStates();
    window.setTimeout(this.initTable,100);

  }
}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.datarow {
    border: 1px solid #eeeeee;
    padding: 0px 0px 0px 0px;
    margin-bottom: 0px;
    &:last-child {
      margin-bottom: 0;
    }
  }

.titlecol{
    font-weight: bold;
}

.labcol {
padding: 3px 3px 3px 5px;
border-radius: 4px;
font-size: 14px;
text-align:right;
border-right: 1px solid #eeeeee;
}

.datacol {
padding: 3px 3px 3px 3px;
border-radius: 0px;
text-align:left;

vertical-align: middle;
border-right: 1px solid #eeeeee;
}

.bgrow{
    background-color: #d4f1ff;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 122px;
    height: 53px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 122px;
    height: 53px;
    display: block;
  }
</style>
